package observer;

import java.util.ArrayList;

/**
 * 事件对象
 */
class WeakUpEvent<T>{
    long time;
    String loc;
    T source;

    public WeakUpEvent(long time, String loc, T source){
        this.time = time;
        this.loc = loc;
        this.source = source;
    }

    @Override
    public String toString() {
        return "WeakUpEvent{" +
                "time=" + time +
                ", loc='" + loc + '\'' +
                '}';
    }
}

/**
 * 观察者接口
 */
interface Observer<T>{
    void weakUp(WeakUpEvent <T>weakUpEvent);
}

/**
 * Child 被观察者
 */
class Child {
    public String tmp = "admin";

    private ArrayList<Observer> observerList = new ArrayList<>();

    public Child add(Observer observer){
        observerList.add(observer);
        return this;
    }

    public void weakUp() {
        int i = 0;

        for (Observer observer : observerList){
            observer.weakUp(new WeakUpEvent<Child>(System.currentTimeMillis(), "str" + i++, this));
        }

    }
}

/**
 * Parent 观察者
 */
class Parent implements Observer<Child>{

    @Override
    public void weakUp(WeakUpEvent <Child>weakUpEvent) {
        System.out.println("Parent 监控");
        System.out.println(weakUpEvent);
        System.out.println(weakUpEvent.source.tmp);
    }
}

public class ObserverMain {
    public static void main(String[] args) {
        System.out.println("Observer");

        Child child = new Child();
        child.add(new Parent()).add(new Parent()).weakUp();
    }
}
